<?php
require ("userCentreDao.Class.php");
class userCentreLogic
{
    private $m_uDao;
    private $m_memcache_enable;
    private $m_memcache;

    public function __construct()
    {
        $storeConfig = new userCentreConfig();
        $arrConfig = $storeConfig->getStoreConfig();
        $this->m_uDao = new userCentreDao(
            $arrConfig["MongoDB_Host"],
            $arrConfig["MongoDB_Port"],
            $arrConfig["MongoDB_Database"],
            $arrConfig["MongoDB_Table"]
        );
        $this->m_memcache_enable = ($arrConfig["Memcache_Enable"] == 1);
        if ($this->m_memcache_enable)
        {
            $this->m_memcache = new Memcache();
            foreach ($arrConfig["Memcache_Servers"] as $memcache_server)
            {
                $this->m_memcache->addServer($memcache_server["Host"], $memcache_server["Port"]);
            }
        }
    }

    public function __destruct()
    {
        unset($this->m_uDao);
        if ($this->m_memcache_enable)
        {
            $this->m_memcache->close();
        }
    }

    public function getUserInfo($intUserID)
    {
        if ($this->m_memcache_enable)
        {
            $userInfo = $this->m_memcache->get($intUserID);
            if (false == $userInfo)
            {
                echo "cache miss!\n";
                $userInfo = $this->m_uDao->getUserInfo($intUserID);
                if (NULL != $userInfo)
                {
                    $this->m_memcache->set($intUserID, $userInfo);
                }
            }
        }
        return $userInfo;
    }

    public function getUserInfoList($arrUserIDList)
    {
        $hitList = array();
        if ($this->m_memcache_enable)
        {
            $userInfoList_Cache = $this->m_memcache->get($arrUserIDList);
//            var_dump($userInfoList_Cache);
            foreach($userInfoList_Cache as $userInfo)
            {
                $hitList[] = $userInfo["_id"];
            }
            $missList = array_diff($arrUserIDList, $hitList);
//            var_dump($missList);
            if (0 != count($missList))
            {
                echo "cache miss!\n";
                $userInfoList_Mongo = $this->m_uDao->getUserInfoList($missList);
                foreach($userInfoList_Mongo as $userInfo)
                {
                    $this->m_memcache->set($userInfo["_id"], $userInfo);
                }
            }
        }
        return array_merge($userInfoList_Cache, $userInfoList_Mongo);
    }


    public function setUserInfo($intUserID, $arrUserInfo)
    {
        $this->m_uDao->setUserInfo($intUserID, $arrUserInfo);
        $this->m_memcache->delete($intUserID);
        return $this->getUserInfo($intUserID);
    }
};
?>
